package cn.ichiva.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateUtils {

    /** 紧凑型 */
    public static String FORMAT_SMART_DD = "yyyyMMdd";
    public static String FORMAT_SMART_MONTH = "yyyyMM";

    /** 常规型 */
    public static String FORMAT_TO_MONTH = "yyyy-MM";
    public static String FORMAT_TO_DD = "yyyy-MM-dd";
    public static String FORMAT_TO_HH = "yyyy-MM-dd HH";
    public static String FORMAT_TO_MM = "yyyy-MM-dd HH:mm";
    public static String FORMAT_TO_SS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 字符串转日期
     * @param dateStr
     * @param format
     * @return
     */
    public static Date toDate(String dateStr, String format){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期转字符串
     * @param dateStr
     * @param format
     * @return
     */
    public static String toString(Date dateStr, String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(dateStr);
    }

    /**
     * 当天剩余时间（毫秒）
     */
    public static long remainingTimeForDay(){
        return ChronoUnit.MILLIS.between(LocalDateTime.now(),LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
    }

    /**
     * 距离下一个小时数的时间（毫秒）
     * @param nHour
     * @return
     */
    public static long remainingTimeForNextHour(int nHour){
        int hour = LocalTime.now().getHour();
        int remainingHour = hour < nHour ? nHour -24 : nHour;
        return remainingTimeForDay() + remainingHour * 1000 * 60 * 60;
    }
}
